package org.jeecg.modules.lab.chemical.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.lab.chemical.entity.LabChemical;
import org.jeecg.modules.lab.chemical.entity.LabChemicalUsed;
import org.jeecg.modules.lab.chemical.entity.LabChemicalUsedDescribe;
import org.jeecg.modules.lab.chemical.entity.LabChemicalUsedTo;
import org.jeecg.modules.lab.chemical.service.ILabChemicalService;
import org.jeecg.modules.lab.chemical.service.ILabChemicalUsedDescribeService;
import org.jeecg.modules.lab.chemical.service.ILabChemicalUsedService;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 标物领用记录表
 * @Author: jeecg-boot
 * @Date: 2023-08-15
 * @Version: V1.0
 */
@Api(tags = "标物领用记录表")
@RestController
@RequestMapping("/chemical/labChemicalUsed")
@Slf4j
public class LabChemicalUsedController extends JeecgController<LabChemicalUsed, ILabChemicalUsedService> {
    @Autowired
    private ILabChemicalUsedService labChemicalUsedService;

    @Autowired
    private ILabChemicalUsedDescribeService labChemicalUsedDescribeService;

    @Autowired
    private ILabChemicalService labChemicalService;

    @Autowired
    private ILabCronJobService labCronJobService;

    /**
     * 分页列表查询
     *
     * @param labChemicalUsed
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "标物领用记录表-分页列表查询")
    @ApiOperation(value = "标物领用记录表-分页列表查询", notes = "标物领用记录表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabChemicalUsed>> queryPageList(LabChemicalUsed labChemicalUsed,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<LabChemicalUsed> queryWrapper = QueryGenerator.initQueryWrapper(labChemicalUsed, req.getParameterMap());
        Page<LabChemicalUsed> page = new Page<LabChemicalUsed>(pageNo, pageSize);
        IPage<LabChemicalUsed> pageList = labChemicalUsedService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param labChemicalUsedTo
     * @return
     */
    @AutoLog(value = "标物领用记录表-添加")
    @ApiOperation(value = "标物领用记录表-添加", notes = "标物领用记录表-添加")
//   @RequiresPermissions("chemicalUsed:lab_chemical_used:add")
    @PostMapping(value = "/add")
    @Transactional
    public Result<String> add(@RequestBody LabChemicalUsedTo labChemicalUsedTo) {
        LabChemicalUsed labChemicalUsed = new LabChemicalUsed();
        //拷贝属性
        BeanUtils.copyProperties(labChemicalUsedTo, labChemicalUsed);
        labChemicalUsed.setCreateTime(new Date());
        labChemicalUsed.setId(UUID.randomUUID().toString());
        //将领用记录的id放入清单中作为chemicalId
        labChemicalUsedTo.getListDescribe().stream().forEach(e -> {

            e.setUsedId(labChemicalUsed.getId());
            e.setId(UUID.randomUUID().toString());
            Double outNumber = e.getOutNumber();
            if (outNumber != null) {
                //出库记录
                Double inventoryNow =e.getInventoryNow();
                if (inventoryNow - outNumber >= 0) {
                    //修改存量
                    e.setInventoryNow(inventoryNow - outNumber);
                } else {
                    throw new RuntimeException("库存不足");
                }
            } else if (e.getPutNumber()!=null){
                //入库记录
                e.setInventoryNow(e.getInventoryNow()+e.getPutNumber());
            }
        });
        labChemicalUsedService.save(labChemicalUsed);
        labChemicalUsedDescribeService.saveBatch(labChemicalUsedTo.getListDescribe());
        //修改基础表
        // 设置更新条件，例如根据 chemicalId 更新
        List<LabChemical> list = new ArrayList();
        // 构建需要更新的字段和值
        labChemicalUsedTo.getListDescribe().forEach(e -> {
            // 获取需要更新的字段和值
            String chemicalId =  e.getChemicalId();
            Double inventoryNow =  e.getInventoryNow();
            LabChemical labChemical = new LabChemical();
            labChemical.setInventoryNow(inventoryNow);
            labChemical.setId(chemicalId);
            labChemical.setSynFlag("1");
            list.add(labChemical);
        });
        labChemicalService.updateBatchById(list);


        if (MyEnum.sync) {
            long time = new Date().getTime();
            ArrayList<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_chemical_used", "0", time, 1));
            jobs.add(new LabCronJob("lab_chemical_used_describe", "0", time, 2));
            jobs.add(new LabCronJob("lab_chemical", "1", time, 3));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labChemicalUsed
     * @return
     */
    @AutoLog(value = "标物领用记录表-编辑")
    @ApiOperation(value = "标物领用记录表-编辑", notes = "标物领用记录表-编辑")
//   @RequiresPermissions("chemicalUsed:lab_chemical_used:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabChemicalUsed labChemicalUsed) {
        labChemicalUsedService.updateById(labChemicalUsed);


        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "标物领用记录表-通过id删除")
    @ApiOperation(value = "标物领用记录表-通过id删除", notes = "标物领用记录表-通过id删除")
//   @RequiresPermissions("chemicalUsed:lab_chemical_used:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        LambdaQueryWrapper<LabChemicalUsedDescribe> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabChemicalUsedDescribe::getUsedId, id);
        List<LabChemicalUsedDescribe> queryList = labChemicalUsedDescribeService.list(wrapper);
        if (queryList.isEmpty()) {
            labChemicalUsedService.removeById(id);
            return Result.OK("删除成功!");
        } else {
            return Result.error("确认删除清单信息");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "标物领用记录表-批量删除")
    @ApiOperation(value = "标物领用记录表-批量删除", notes = "标物领用记录表-批量删除")
//   @RequiresPermissions("chemicalUsed:lab_chemical_used:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labChemicalUsedService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "标物领用记录表-通过id查询")
    @ApiOperation(value = "标物领用记录表-通过id查询", notes = "标物领用记录表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabChemicalUsed> queryById(@RequestParam(name = "id", required = true) String id) {
        LabChemicalUsed labChemicalUsed = labChemicalUsedService.getById(id);
        if (labChemicalUsed == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labChemicalUsed);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labChemicalUsed
     */
//   @RequiresPermissions("chemicalUsed:lab_chemical_used:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabChemicalUsed labChemicalUsed) {
        return super.exportXls(request, labChemicalUsed, LabChemicalUsed.class, "标物领用记录表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//   @RequiresPermissions("chemicalUsed:lab_chemical_used:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LabChemicalUsed.class);
    }

}
